import React from 'react';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import {
  Card,
  Form,
  Input,
  Button,
  message,
  Modal,
  InputNumber,
  Space,
  Radio,
  Row,
  Col,
  Tag,
  Slider,
  Table,
} from 'antd';
import { ExclamationCircleOutlined, PushpinOutlined } from '@ant-design/icons';
import { connect } from 'umi';
import G2Line from '../Charts/G2Line';

const currControl = 'Edu_PrematureBabyCurve';
const { confirm } = Modal;
class ViewPage extends React.Component<any, any> {
  constructor(props: any) {
    super(props);
    this.state = {
      loading: false,
      loading2: false,
      datas: {},
      pageSize: 10,
      GrowthData: [],
      dataSource: [],
      sex: 1,
      btype: 1,
      age: 0,
      minAge: 0,
      maxAge: 60,
    };
  }

  formRef: any = React.createRef();
  componentDidMount() {
    this.fetchGrowthData();
  }
  onFinish = async (values: any) => {
    this.setState({ loading2: true });
    var act = 'Abp/create';
    if (values.model.id) {
      act = 'Abp/update';
    }
    this.props
      .dispatch({
        type: act,
        payload: values.model,
        control: currControl,
      })
      .then(() => {
        var resp = this.props.response;
        if (resp.success) {
          message.success('保存成功！');
          this.setState({ loading2: false });
          this.fetchGrowthData();
        } else {
          message.error('保存错误，请联系管理员');
        }
      });
  };
  fetchDatas = (value: number) => {
    const { sex, btype } = this.state;
    this.props
      .dispatch({
        type: 'Abp/getList',
        payload: { sex, btype },
        control: currControl,
      })
      .then(() => {
        const { sex, btype } = this.state;
        var resp = this.props.response;
        if (resp) {
          var datas = resp.result.items.filter(
            (o: any) => o.gestationalAge == value && o.babySex == sex && o.babyType == btype,
          )[0];
          if (datas) {
            this.formRef.current.setFieldsValue({ model: datas });
            this.setState({ datas });
          } else {
            this.formRef.current.resetFields();
          }
        }
      });
  };
  fetchCurrent = (id: any) => {
    this.setState({ loading2: true });
    this.props
      .dispatch({
        type: 'Abp/get',
        payload: { id },
        control: currControl,
      })
      .then(() => {
        var resp = this.props.response;
        console.log(resp);
        if (resp) {
          var datas = resp.result;
          if (datas) {
            this.formRef.current.setFieldsValue({ model: datas });
            this.setState({ datas, loading2: false });
          } else {
            this.formRef.current.resetFields();
          }
        }
      });
  };
  fetchGrowthData = () => {
    const { sex, btype, minAge, maxAge } = this.state;
    this.setState({ loading: true });
    this.props
      .dispatch({
        type: 'Abp/getList',
        payload: { sex, btype, minAge, maxAge },
        control: currControl,
      })
      .then(() => {
        var resp = this.props.response;
        if (resp) {
          var dataSource = resp.result.items;
          var gdata: any = [];
          dataSource.forEach((element: any) => {
            let obj = {
              day: element.gestationalAge,
              ctype: '身高-3th',
              value: element.heightThree,
            };
            gdata.push(obj);
            obj = {
              day: element.gestationalAge,
              ctype: '身高-10th',
              value: element.heightTen,
            };
            gdata.push(obj);
            obj = {
              day: element.gestationalAge,
              ctype: '身高-50th',
              value: element.heightFifty,
            };
            gdata.push(obj);
            obj = {
              day: element.gestationalAge,
              ctype: '身高-90th',
              value: element.heightNinty,
            };
            gdata.push(obj);
            obj = {
              day: element.gestationalAge,
              ctype: '身高-97th',
              value: element.heightNintySeven,
            };
            gdata.push(obj);
            //体重
            obj = {
              day: element.gestationalAge,
              ctype: '体重-3th',
              value: element.weightThree,
            };
            gdata.push(obj);
            obj = {
              day: element.gestationalAge,
              ctype: '体重-10th',
              value: element.weightTen,
            };
            gdata.push(obj);
            obj = {
              day: element.gestationalAge,
              ctype: '体重-50th',
              value: element.weightFifty,
            };
            gdata.push(obj);
            obj = {
              day: element.gestationalAge,
              ctype: '体重-90th',
              value: element.weightNinty,
            };
            gdata.push(obj);
            obj = {
              day: element.gestationalAge,
              ctype: '体重-97th',
              value: element.weightNintySeven,
            };
            gdata.push(obj);
            //头围
            obj = {
              day: element.gestationalAge,
              ctype: '头围-3th',
              value: element.headThree,
            };
            gdata.push(obj);
            obj = {
              day: element.gestationalAge,
              ctype: '头围-10th',
              value: element.headTen,
            };
            gdata.push(obj);
            obj = {
              day: element.gestationalAge,
              ctype: '头围-50th',
              value: element.headFifty,
            };
            gdata.push(obj);
            obj = {
              day: element.gestationalAge,
              ctype: '头围-90th',
              value: element.headNinty,
            };
            gdata.push(obj);
            obj = {
              day: element.gestationalAge,
              ctype: '头围-97th',
              value: element.headNintySeven,
            };
            gdata.push(obj);
          });
          this.setState({ GrowthData: gdata, dataSource, loading: false });
          this.g2LineBsc.loadData();
        }
      });
  };
  ResetForm = () => {
    var data = {
      id: 0,
    };
    this.setState({ datas: data });
    this.formRef.current.resetFields();
  };
  handleDel = () => {
    this.props
      .dispatch({
        type: 'Abp/delete',
        payload: { Id: this.state.datas.id },
        control: currControl,
      })
      .then(() => {
        var resp = this.props.response;
        if (resp.success) {
          message.success('删除成功！');
          this.formRef.current.resetFields();
        } else {
          message.error('删除错误，请联系管理员！');
        }
      });
  };
  showConfirm = () => {
    var _this = this;
    confirm({
      title: '警告',
      icon: <ExclamationCircleOutlined />,
      content: '删除后将不可恢复，确定删除？',
      onOk() {
        _this.handleDel();
      },
      onCancel() {},
    });
  };
  handleSexChange = (e: any) => {
    let that = this;
    this.setState({ sex: e.target.value }, function () {
      that.fetchGrowthData();
    });
  };
  handleTypeChange = (e: any) => {
    let that = this;
    this.setState({ btype: e.target.value }, function () {
      that.fetchGrowthData();
    });
  };
  CopyData = () => {
    let model = this.state.datas;
    model.id = undefined;
    model.gestationalAge += 1;
    var act = 'Abp/create';
    this.props
      .dispatch({
        type: act,
        payload: model,
        control: currControl,
      })
      .then(() => {
        var resp = this.props.response;
        if (resp.success) {
          message.success('复制成功！');
          this.formRef.current.setFieldsValue({ model });
          this.fetchGrowthData();
        } else {
          message.error('保存错误，请联系管理员');
        }
      });
  };
  g2LineBsc: any = React.createRef();
  onRef = (ref: any) => {
    this.g2LineBsc = ref;
  };
  onAfterChange = (value: any) => {
    let that = this;
    this.setState({ minAge: value[0], maxAge: value[1] }, function () {
      that.fetchGrowthData();
    });
  };
  render() {
    const { datas, loading, loading2, sex, btype, GrowthData, dataSource } = this.state;
    const columns = [
      {
        title: '月龄',
        dataIndex: 'gestationalAge',
        render: (text: number, record: any) => (
          <span>
            {text}
            {record.babyType === 1 ? '月' : record.babyType === 2 ? '月' : '周'}
          </span>
        ),
      },
      {
        title: '性别',
        dataIndex: 'babySex',
        render: (text: number) => <Tag>{text === 1 ? '男' : '女'}</Tag>,
      },
      {
        title: '类型',
        dataIndex: 'babyType',
        render: (text: number) => (
          <span>{text === 1 ? '足月儿（WHO）' : text === 2 ? '足月儿（国内）' : '早产儿'}</span>
        ),
      },
      {
        title: '身高3th',
        dataIndex: 'heightThree',
        render: (text: number) => <span>{text} cm</span>,
      },
      {
        title: '身高50th',
        dataIndex: 'heightFifty',
        render: (text: number) => <span>{text} cm</span>,
      },
      {
        title: '身高97th',
        dataIndex: 'heightNintySeven',
        render: (text: number) => <span>{text} cm</span>,
      },
      {
        title: '体重3th',
        dataIndex: 'weightThree',
        render: (text: number) => <span>{text} kg</span>,
      },
      {
        title: '体重50th',
        dataIndex: 'weightFifty',
        render: (text: number) => <span>{text} kg</span>,
      },
      {
        title: '体重97th',
        dataIndex: 'weightNintySeven',
        render: (text: number) => <span>{text} kg</span>,
      },
      {
        title: '头围3th',
        dataIndex: 'headThree',
        render: (text: number) => <span>{text} cm</span>,
      },
      {
        title: '头围50th',
        dataIndex: 'headFifty',
        render: (text: number) => <span>{text} cm</span>,
      },
      {
        title: '头围97th',
        dataIndex: 'headNintySeven',
        render: (text: number) => <span>{text} cm</span>,
      },
    ];
    const rowSelection = {
      onChange: (selectedRowKeys: any, selectedRows: any) => {
        this.fetchCurrent(selectedRowKeys);
      },
    };
    return (
      <PageHeaderWrapper>
        <Row gutter={[16, 16]}>
          <Col span={24}>
            <Card>
              <Table
                rowKey="id"
                size="small"
                loading={loading}
                columns={columns}
                dataSource={dataSource}
                rowSelection={{
                  type: 'radio',
                  ...rowSelection,
                }}
                onRow={(record) => {
                  return {
                    onClick: (event) => {},
                    onDoubleClick: (event) => {
                      this.fetchCurrent(record.id);
                    },
                  };
                }}
              />
            </Card>
          </Col>
          <Col span={14}>
            <Card>
              <Form ref={this.formRef} layout="vertical" onFinish={this.onFinish}>
                <div style={{ display: 'none' }}>
                  <Form.Item label="id" name={['model', 'id']}>
                    <Input />
                  </Form.Item>
                </div>
                <Form.Item label="胎龄" style={{ marginBottom: 0 }}>
                  <Input.Group compact>
                    <Form.Item
                      name={['model', 'gestationalAge']}
                      rules={[{ required: true, message: '请输入孕周' }]}
                    >
                      <InputNumber onChange={(value: any) => this.setState({ age: value })} />
                    </Form.Item>
                    <Form.Item>
                      <Button
                        icon={<PushpinOutlined />}
                        onClick={() => this.fetchDatas(this.state.age)}
                      ></Button>
                    </Form.Item>
                  </Input.Group>
                </Form.Item>
                <Form.Item name={['model', 'babySex']}>
                  <Radio.Group>
                    <Radio value={1}>男孩</Radio>
                    <Radio value={0}>女孩</Radio>
                  </Radio.Group>
                </Form.Item>
                <Form.Item name={['model', 'babyType']}>
                  <Radio.Group>
                    <Radio value={0}>早产儿</Radio>
                    <Radio value={1}>足月儿</Radio>
                    <Radio value={2}>足月儿（国内）</Radio>
                  </Radio.Group>
                </Form.Item>
                <Form.Item style={{ marginBottom: 0 }}>
                  <Input.Group compact>
                    <Form.Item name={['model', 'headThree']} label="头围3">
                      <InputNumber />
                    </Form.Item>
                    {/* <Form.Item name={['model', 'headFive']} label="头围5">
                      <InputNumber />
                    </Form.Item> */}
                    <Form.Item name={['model', 'headTen']} label="头围10">
                      <InputNumber />
                    </Form.Item>
                    {/* <Form.Item name={['model', 'headFifteen']} label="头围15">
                      <InputNumber />
                    </Form.Item> */}
                    <Form.Item name={['model', 'headFifty']} label="头围50">
                      <InputNumber />
                    </Form.Item>
                    {/* <Form.Item name={['model', 'headEightyFive']} label="头围85">
                      <InputNumber />
                    </Form.Item> */}
                    <Form.Item name={['model', 'headNinty']} label="头围90">
                      <InputNumber />
                    </Form.Item>
                    {/* <Form.Item name={['model', 'headNintyFive']} label="头围95">
                      <InputNumber />
                    </Form.Item> */}
                    <Form.Item name={['model', 'headNintySeven']} label="头围97">
                      <InputNumber />
                    </Form.Item>
                  </Input.Group>
                </Form.Item>
                <Form.Item style={{ marginBottom: 0 }}>
                  <Input.Group compact>
                    <Form.Item name={['model', 'heightThree']} label="身高3">
                      <InputNumber />
                    </Form.Item>
                    {/* <Form.Item name={['model', 'heightFive']} label="身高5">
                      <InputNumber />
                    </Form.Item> */}
                    <Form.Item name={['model', 'heightTen']} label="身高10">
                      <InputNumber />
                    </Form.Item>
                    {/* <Form.Item name={['model', 'heightFifteen']} label="身高15">
                      <InputNumber />
                    </Form.Item> */}
                    <Form.Item name={['model', 'heightFifty']} label="身高50">
                      <InputNumber />
                    </Form.Item>
                    {/* <Form.Item name={['model', 'heightEightyFive']} label="身高85">
                      <InputNumber />
                    </Form.Item> */}
                    <Form.Item name={['model', 'heightNinty']} label="身高90">
                      <InputNumber />
                    </Form.Item>
                    {/* <Form.Item name={['model', 'heightNintyFive']} label="身高95">
                      <InputNumber />
                    </Form.Item> */}
                    <Form.Item name={['model', 'heightNintySeven']} label="身高97">
                      <InputNumber />
                    </Form.Item>
                  </Input.Group>
                </Form.Item>
                <Form.Item style={{ marginBottom: 0 }}>
                  <Input.Group compact>
                    <Form.Item name={['model', 'weightThree']} label="体重3">
                      <InputNumber />
                    </Form.Item>
                    {/* <Form.Item name={['model', 'weightFive']} label="体重5">
                      <InputNumber />
                    </Form.Item> */}
                    <Form.Item name={['model', 'weightTen']} label="体重10">
                      <InputNumber />
                    </Form.Item>
                    {/* <Form.Item name={['model', 'weightFifteen']} label="体重15">
                      <InputNumber />
                    </Form.Item> */}
                    <Form.Item name={['model', 'weightFifty']} label="体重50">
                      <InputNumber />
                    </Form.Item>
                    {/* <Form.Item name={['model', 'weightEightyFive']} label="体重85">
                      <InputNumber />
                    </Form.Item> */}
                    <Form.Item name={['model', 'weightNinty']} label="体重90">
                      <InputNumber />
                    </Form.Item>
                    {/* <Form.Item name={['model', 'weightNintyFive']} label="体重95">
                      <InputNumber />
                    </Form.Item> */}
                    <Form.Item name={['model', 'weightNintySeven']} label="体重97">
                      <InputNumber />
                    </Form.Item>
                  </Input.Group>
                </Form.Item>

                <Form.Item>
                  <Space>
                    <Button type="primary" htmlType="submit" loading={loading2}>
                      保存
                    </Button>
                    <Button onClick={this.ResetForm}>重设</Button>
                    <Button onClick={this.CopyData} type="primary">
                      复制
                    </Button>
                    <Button danger onClick={this.showConfirm} disabled={!datas.id}>
                      删除
                    </Button>
                  </Space>
                </Form.Item>
              </Form>
            </Card>
          </Col>
          <Col span={10}>
            <Card>
              <Space>
                <Radio.Group defaultValue={sex} value={sex} onChange={this.handleSexChange}>
                  <Radio.Button value="1">男孩</Radio.Button>
                  <Radio.Button value="0">女孩</Radio.Button>
                </Radio.Group>
                <Radio.Group defaultValue={btype} value={btype} onChange={this.handleTypeChange}>
                  <Radio.Button value="0">早产儿</Radio.Button>
                  <Radio.Button value="1">足月儿（WHO） </Radio.Button>
                  <Radio.Button value="2">足月儿（国内）</Radio.Button>
                </Radio.Group>
                <Tag color="success">
                  {this.state.minAge}~{this.state.maxAge}
                </Tag>
              </Space>
              <Slider
                range
                defaultValue={[0, 100]}
                max={800}
                tipFormatter={(value) => {
                  return `${value}`;
                }}
                onAfterChange={this.onAfterChange}
              />

              <G2Line ParentData={GrowthData} onRef={this.onRef} height={500} />
            </Card>
          </Col>
        </Row>
      </PageHeaderWrapper>
    );
  }
}
export default connect(({ Abp }: API.IConnectState) => ({
  response: Abp.response,
  currentUser: Abp.currentUser,
}))(ViewPage);
